package com.philosophy.web.controller;

import com.philosophy.web.cmd.CreateUrlMappingCmd;
import com.philosophy.web.cmd.DeleteUrlMappingCmd;
import com.philosophy.web.service.ShortUrlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author philosophy
 */
@RestController
@RequestMapping("short/url")
@Slf4j
public class ShortUrlController {

    @Resource
    private ShortUrlService shortUrlService;

    /**
     * 创建url映射
     *
     * @param createUrlMappingCmd 命令
     * @return 短url
     */
    @PostMapping
    @ResponseBody
    public String createUrlMapping(@RequestBody CreateUrlMappingCmd createUrlMappingCmd, HttpServletRequest request) {
        String shortUrl = shortUrlService.createUrlMapping(createUrlMappingCmd.getOriginUrl());
        String scheme = request.getScheme();
        int port = request.getLocalPort();
        String address = "wkynf.com";
        String urlFormat = "%s://%s:%d/%s";
        return String.format(urlFormat, scheme, address, port, shortUrl);
    }

    /**
     * todo
     * 删除url映射
     *
     * @param deleteUrlMappingCmd cmd
     * @return 短url
     */
    @DeleteMapping
    public String deleteUrlMapping(DeleteUrlMappingCmd deleteUrlMappingCmd) {
        return shortUrlService.deleteUrlMapping(deleteUrlMappingCmd);
    }

    /**
     * 创建url映射测试
     *
     * @return 短url
     */
    @GetMapping("test")
    public String createUrlTest() {
        String originUrl = "https://www.baidu.com/index.html?a=";
        long start = System.currentTimeMillis();
        int n = 500;
        for (int i = 0; i < n; i++) {
            shortUrlService.createUrlMapping(originUrl + i);
        }
        long end = System.currentTimeMillis();
        log.info("总耗时:" + (end - start) + "ms");
        return "ok";
    }

}
